<script setup>

import {
  CollectionTag,
  Cpu,
  Delete,
  Download,
  FolderAdd,
  Picture,
  Plus,
  UploadFilled,
  ZoomIn
} from "@element-plus/icons-vue";
import Card from "@/components/Card.vue";
import {h, reactive, ref} from "vue";
import {ElMessage, ElNotification} from "element-plus";
import ConnectWallet from "@/components/NFT/ConnectWallet.vue";
import {useStore} from "@/store";
import LightCard from "@/components/LightCard.vue";
import WalletState from "@/components/NFT/WalletState.vue";
import {accessHeader, post} from "@/net";
import axios from "axios";
import router from "@/router";
import {mint} from "@/contract/minner/nft_minner";


const store = useStore()


//测试图片
const bannerImg = ref([
  'https://images6.alphacoders.com/429/429308.png',
  'https://images7.alphacoders.com/786/786210.png',
  'https://images7.alphacoders.com/429/429307.png',
])


//表单数据
const uploadRef = ref()
const upload = reactive({
  fileName:'',
  title:'',
  description:''
})
const aiRef = ref()
const ai = reactive({
  type:'像素风格',
  fileName:'',
  title:'',
  description:'',
  keywords:''
})
const ipfsBase = 'http://127.0.0.1:8081/ipfs/'
const initURL = ipfsBase+'QmRm5KRfiZvwsK4VbPwoiVAU7KYAuiPRVQoDDxsDUbpKBS'
const imageURL = ref(initURL)
const metadataURL = ref('')
//mint数据
const mintData = reactive({
  title:'',
  description:'',
  url:''
})

//Ai绘画
const defaultPar = reactive({
  types:[
      '写实风格','二次元风格','像素风格','抽象风格','逆天风格'
  ],
})

//AI绘画
const aiDraw = ()=>{
  if(ai.keywords.length === 0){
    ElMessage.warning("请输入关键词")
    return
  }else if (ai.title.length === 0){
    ElMessage.warning("请输入标题")
    return
  }else if(ai.description.length === 0){
    ElMessage.warning("请输入作品描述")
    return
  }
  const key = ai.keywords + "，风格为" + ai.type
  //1.调用tx服务
  post('/api/nft/ai',{
    keyword: key
  },data=>{
    ElMessage.success("绘制成功！")
    imageURL.value = ipfsBase+data
    //封装数据
    mintData.url = imageURL.value
    mintData.title = ai.title
    mintData.description = ai.description
  })
}


//撤销
const handleUndo = () => {
  upload.title = ''
  upload.description = ''
  upload.fileName = ''
  ai.title = ''
  ai.description = ''
  ai.keywords = ''
  ai.fileName = ''
  imageURL.value = initURL
}
//上传检查
const beforeUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error("头像只能是jpg/png")
    return false
  }else if(rawFile.size / (1024*1024) > 10){
    ElMessage.error("图片大小不能大于10Mb")
    return false
  }else {
    upload.fileName = rawFile.name
    return true
  }
}
//上传成功
function uploadSuccess(response){
  ElMessage.success("作品上传成功")
  imageURL.value = ipfsBase+response.data
  mintData.title = upload.title
  mintData.description = upload.description
  mintData.url = imageURL.value
}

//mintNow
const mintNow = async ()=>{
  //检查是否有文件
  if (imageURL.value === initURL){
    ElMessage.warning("请先上传一张本地图片！")
    return
  }else if(mintData.title.length === 0){
    ElMessage.warning("请填写标题！")
    return
  }else if(mintData.description.length === 0){
    ElMessage.warning("请填写说明！")
    return
  }
  //构造metadata
  const metadata = {
    title:mintData.title,
    description:mintData.description,
    image:mintData.url
  }
  //上传metadata到ipfs
  await post('/api/nft/metadata',metadata,(data)=>{
    // TODO:一定要toString
    metadataURL.value = (ipfsBase+data).toString()
    //挖一个nft给用户
    mint(store.wallet.address,metadataURL.value)
    ElMessage.success("恭喜您成功mint一件NFT藏品！！")
    handleUndo()
  })
}

//初始化
function init(){

}
init()


</script>

<template>
  <el-carousel style="max-width: 1000px;margin: auto" type="card" height="250px">
    <el-carousel-item v-for="item in 3" :key="item">
      <el-image :src="bannerImg[item-1]"/>
    </el-carousel-item>
  </el-carousel>
  <div style="display: flex;max-width: 1000px;margin: auto">
    <div class="mint" v-if="store.wallet.connected" style="width: 700px">
      <!--      aiMint-->
      <div class="mint-left">
        <Card :icon="Cpu"
              title="Created By AI"
              desc="AI将会帮您铸造一个独一无二的NFT艺术品 (由腾讯云服务支持)">
          <div>
            <el-tag type="info" style="margin-right: 20px;font-size: 16px;">请选择一种基础风格</el-tag>
            <el-select v-model="ai.type" style="width: 150px;">
              <el-option v-for="item in defaultPar.types" :label="item" :value="item"/>
            </el-select>
          </div>
          <div style="margin-top: 10px">
            <el-form :model="ai" ref="aiRef" label-position="top" style="margin: 0 10px 10px 10px">
              <el-form-item label="标题" prop="title">
                <el-input v-model="ai.title" placeholder="请输入作品标题"/>
              </el-form-item>
              <el-form-item label="描述" prop="description">
                <el-input type="textarea"
                          v-model="ai.description"
                          maxlength="150"
                          placeholder="请输入作品描述"/>
              </el-form-item>
              <el-form-item label="关键字" prop="keywords">
                <el-input  style="height: 130px;" v-model="ai.keywords" placeholder="请输入其他关键词，例如：一只会飞的小猫"/>
              </el-form-item>
            </el-form>
          </div>
          <div style="text-align: center;font-size: 15px;margin-top: 20px;margin-bottom: 20px">
            <el-button style="width: 120px;height: 50px" type="primary" @click="aiDraw">绘制</el-button>
            <el-button style="width: 120px;height: 50px" type="success" @click="mintNow">Mint Now</el-button>
          </div>
        </Card>
      </div>
      <!--      手动上传-->
      <div class="mint-right">
        <Card
            :icon="FolderAdd"
            title="Upload Your Artwork"
            desc="上传您自己的作品">
          <div style="margin: 10px">
            <el-form :model="upload" ref="uploadRef" label-position="top" style="margin: 0 10px 10px 10px">
              <el-form-item label="标题" prop="title">
                <el-input v-model="upload.title" placeholder="请输入作品标题"/>
              </el-form-item>
              <el-form-item label="描述" prop="description">
                <el-input type="textarea"
                          v-model="upload.description"
                          maxlength="150"
                          placeholder="请输入作品描述"/>
              </el-form-item>
              <div style="margin-bottom: 10px">文件</div>
              <el-form-item>
                <el-upload
                    :action="axios.defaults.baseURL+'/api/nft/upload'"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    :headers="accessHeader()">
                  <el-button type="info" size="large">上传文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip text-red">
                      limit 1 file, new file will cover the old file
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-form>
            <div style="text-align: center;font-size: 15px;margin-top: 20px">
              <el-button style="width: 120px;height: 50px" type="warning" @click="handleUndo">撤回</el-button>
              <el-button style="width: 120px;height: 50px" type="success" @click="mintNow">Mint Now</el-button>
            </div>
          </div>
        </Card>
      </div>
    </div>
    <div class="other" style="flex: 1;margin: 20px">
      <Card style="margin-top: 15px">
        <div style="font-weight: bold">
          <el-icon><CollectionTag/></el-icon>
          版块介绍
        </div>
        <el-divider style="margin: 10px"/>
        <div style="font-size: 14px;margin: 10px;color: grey;text-indent: 2em">
          <p>欢迎来到我们的铸造NFT板块！在这里，您可以利用两种不同的方式创作独一无二的NFT艺术品。首先，您可以通过上传您自己的图片来铸造NFT，将您的作品永久记录在区块链上，并确保其唯一性和不可复制性。其次，您还可以利用我们强大的人工智能技术，通过输入关键词调用AI进行绘画，创作出令人惊叹的艺术品，然后将其铸造成NFT。</p>
          <p>赶快开始您的铸造NFT之旅吧，展示您独特的艺术视角，留下属于您自己的数字艺术传世之作！</p>
        </div>
      </Card>
      <wallet-state/>
      <Card :icon="Picture"
            title="效果预览"
            v-if="store.wallet.connected">
        <el-image :src="imageURL"/>
        <div v-if="upload.title.length || ai.title.length">
          名称：{{ai.title || upload.title}}
        </div>
        <div v-if="upload.description.length || ai.description.length">
          描述：{{ai.description || upload.description}}
        </div>
      </Card>
    </div>
  </div>
</template>

<style scoped>
.mint-left{
  margin: 20px;
}
.mint-right{
  margin: 20px;
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
  text-align: center;
}


.image-preview banner-img {
  max-width: 100%;
  max-height: 100%;
}

.upload-placeholder i {
  font-size: 32px;
  margin-bottom: 10px;
}

.input-container .el-input {
  flex: 1;
  margin-right: 10px;
}

.input-container .el-button {
  cursor: pointer;
}

.nft-preview banner-img {
  width: 300px;
  height: auto;
}
</style>